<?php

namespace app\api\controller;

use app\common\exception\BaseException;
use think\Controller as ThinkController;
use think\facade\Log;
use think\Db;

/**
 * API控制器基类
 * Class BaseController
 * @package app\store\controller
 */
class Controller extends ThinkController
{
    const JSON_SUCCESS_STATUS = 1;
    const JSON_ERROR_STATUS = 0;

    /* @ver $wxapp_id 小程序id */
    protected $wxapp_id;

    /**
     * 基类初始化
     * @throws BaseException
     */
    public function _initialize()
    {
        // 当前小程序id
        $this->wxapp_id = $this->getWxappId();
    }

    /**
     * 获取当前小程序ID
     * @return mixed
     * @throws BaseException
     */
    private function getWxappId()
    {
        if (!$wxapp_id = $this->request->param('wxapp_id')) {
            throw new BaseException(['msg' => '缺少必要的参数：wxapp_id']);
        }
        return $wxapp_id;
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderJson($code = self::JSON_SUCCESS_STATUS, $msg = '', $data = [])
    {
        return json(compact('code', 'msg', 'data'));
    }

    /**
     * 返回操作成功json
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderSuccess($data = [], $msg = 'success')
    {
        return $this->renderJson(self::JSON_SUCCESS_STATUS, $msg, $data);
    }

    /**
     * 返回操作失败json
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderError($msg = 'error', $log =false, $data = null)
    {
        if($log ==true){
            $str="";
            if($data != null){
                $str  = " - data=> ". json_encode($data);
            }
            $param=" - param=> ".json_encode($this->request->param());
            Log::record($msg.$param.$str,'emergency');
        }
        if($data == null){
            $data = [];
        }
        return $this->renderJson(self::JSON_ERROR_STATUS, $msg, $data);
    }

    protected function errLog($msg = 'error')
    {
        Log::record($msg,'emergency');
    }
   

     /**
     * 返回操作成功json
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderSuccess_200($err_msg)
    {
        $obj["r_code"]=200;
        $obj["err_msg"]=$err_msg;
        $str = json_encode($obj,JSON_PRETTY_PRINT);
        $Len = strlen($str);
        header('Content-Type: application/json');
        header("Content-Length: $Len");
        echo $str;
        exit();
    }
 
//0  16 17 18  20 的正确输出 
//7b  32 30 30  oa
// \u007b \u0032 \u0030 \u0030 \u000a
//过去第0位是7B就是｛这没错，200在第16、17、18位，第20位是回车（ASCII码是0A）
    protected function renderSuccess_200200($err_msg)
    {
        $obj["r_code"]=200;
        $obj["err_msg"]=$err_msg;
        $str = json_encode($obj,JSON_FORCE_OBJECT);
        $Len = strlen($str);
        header("Content-Length: $Len");
        echo $str;
        exit();
    }


    /**
     * 返回操作失败json
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderError_400($err_msg,$errid)
    {
        Log::write('$card wash error - '.$err_msg);
		if(!empty($errid)){
			Db::table('cardwash_log')->where('id',$errid)->update(['msg' => $err_msg]);
        }
        
        $obj["r_code"]=400;
        $obj["err_msg"]=$err_msg;
        $str = json_encode($obj,JSON_PRETTY_PRINT);
        $Len = strlen($str);
        header('Content-Type: application/json');
        header("Content-Length: $Len");
        echo $str;
        exit();

        // $err_code=400;
        // Log::write('$card wash error - '.$err_msg);
		// if(!empty($errid)){
		// 	Db::table('cardwash_log')->where('id',$errid)->update(['msg' => $err_msg]);
		// }
        // return json(compact('err_code', 'err_msg'));
    }

    /**
     * 获取post数据 (数组)
     * @param $key
     * @return mixed
     */
    protected function postData($key)
    {
        return $this->request->post($key . '/a');
    }

}
